<?php

namespace App\Console\Commands;

use App\Libs\AudioTemplateConf;
use App\Models\Merchant;
use App\Models\TradeDetail;
use App\Models\User;
use App\Models\UserWx;
use App\Models\Wxuser;
use App\Models\WxuserMerchant;
use Illuminate\Support\Facades\Cache;

class GearApiCommand extends GearCommandBase
{
    protected $signature = 'command:gear:api';
    protected $description = 'Gearman Working: yqbassis api around functions.';

    public function workMerchantminilogin($dataOri, $data, $bizContent, $bizContentFormat)
    {

        try{
            $wxuser_info = app('WechatMiniPro')->auth->session($bizContentFormat['wxmini_code']);

            //$wxuser_info['unionid'] = 'o_tjmt5RvVQrYWNAruaUWaQFBbpA';

            if(!empty($wxuser_info['unionid'])){
                $userwx = UserWx::where('union_id', $wxuser_info['unionid'])->first();

                if($userwx){
                    $user = $userwx->user()->first();
                }else{
                    $this->_formatResult->setError('MERCHANT.NOTFOUND');
                    return $this->_signReturn($this->_formatResult->getData());
                }


                if(!empty($user) && $user->role=='merchant'){
                    $merchant = Merchant::where('id_merchant', $user->id_merchant)->first();
                    $today_sum = TradeDetail::where('id_merchant',$user->id_merchant)->where('trade_status','1')->where('createtime', 'like', '%'.date('Y-m-d').'%')->sum('amount_due');

                    $today_sum = round($today_sum/100,2);

                    if(!empty($merchant)){
                        $merchant_data = $merchant->toArray();
                        $merchant_data['today_sum'] = $today_sum;

                        $src_arrs = \Cache::get($bizContentFormat['type'].'_'.$merchant_data['id_merchant'])??[];

                        $this->_formatResult->setSuccess([
                            'wxuser' => $userwx->toArray(),
                            'merchant' => $merchant_data,
                            'voice_data' => $src_arrs,
                        ]);

                        return $this->_signReturn($this->_formatResult->getData());
                    }
                }
                $this->_formatResult->setError('MERCHANT.NOTFOUND');

            }else{
                $this->_formatResult->setError('WECHAT.WXMINICODE.INVALID');
            }

        }catch (\Exception $exception){
            $err_msg = $exception->getMessage();
            dump($err_msg);
            $this->_formatResult->setError('SYS.ERR',['msg' => $err_msg]);
            return $this->_signReturn($this->_formatResult->getData());
        }

        return $this->_signReturn($this->_formatResult->getData());

    }

    public function workVoicenotifymini($dataOri, $data, $bizContent, $bizContentFormat)
    {
        if(!key_exists($bizContentFormat['template_id'],AudioTemplateConf::TEMPLATE)){
            $this->_formatResult->setError('TEMPLATE.ID.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }

        if(!key_exists($bizContentFormat['type'],AudioTemplateConf::TYPE)){
            $this->_formatResult->setError('TYPE.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }
        $template_info = AudioTemplateConf::TEMPLATE[$bizContentFormat['template_id']];
        $voice_type = AudioTemplateConf::TYPE[$bizContentFormat['type']];

        if(empty($bizContentFormat['id_merchant'])){
            $this->_formatResult->setError('ID.MERCHANT.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }

        if(empty($bizContentFormat['template_id']) || empty($template_info)){
            $this->_formatResult->setError('TEMPLATE.ID.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }
        if(empty($voice_type) || !in_array($bizContentFormat['template_id'],$voice_type)){
            $this->_formatResult->setError('TYPE.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }

        if(!empty($template_info['params'])){
            if(empty($bizContentFormat['template_params']) || count($template_info['params']) != count($bizContentFormat['template_params'])){
                $this->_formatResult->setError('TEMPLATE.PARAMS.INVALID');
                return $this->_signReturn($this->_formatResult->getData());
            }
            foreach ($template_info['params'] as $param){
                if(!key_exists($param, $bizContentFormat['template_params'])){
                    $this->_formatResult->setError('TEMPLATE.PARAMS.INVALID');
                    return $this->_signReturn($this->_formatResult->getData());
                }
            }
        }

        $voice_data = $this->_baidutts->getAudioSrc($bizContentFormat['template_id'], $bizContentFormat['template_params']);

        if($voice_data){
            $cache_datas = \Cache::get($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'])??[];

            $today_sum = TradeDetail::where('id_merchant',$bizContentFormat['id_merchant'])->where('trade_status','1')->where('createtime', 'like', '%'.date('Y-m-d').'%')->sum('amount_due');
            $today_sum = round($today_sum/100,2);
            if(!empty($bizContentFormat['order']['id_tradedetail'])){
                $order_model = TradeDetail::where('id_tradedetail',$bizContentFormat['order']['id_tradedetail'])->with('wxuser')->first();

                if(!$order_model || empty($order_model->wxuser)){
                    $this->_formatResult->setError('TRADEDEATIL.ID.INVALID');
                    return $this->_signReturn($this->_formatResult->getData());
                }
            }else{
                $this->_formatResult->setError('TRADEDEATIL.ID.INVALID');
                return $this->_signReturn($this->_formatResult->getData());
            }

            $order_data = [
                'paytime_text' => $order_model->paytime,
                'amount_due' => $order_model->amount_due,
                'out_tradeno' => $order_model->out_tradeno,
                'wxuser' => [
                    'nickname' => $order_model->wxuser->nickname,
                    'avatar_url' => $order_model->wxuser->avatar_url,
                ],
            ];

            $new_data = [
                'type' => $bizContentFormat['type'],
                'voice_src' => $voice_data['voice_src'],
                'today_sum' => $today_sum,
                'rel_text' => $voice_data['rel_text'],
                'order' => $order_data,
            ];

            array_push($cache_datas,$new_data);

            $fd = Cache::get($bizContentFormat['id_merchant']);
            if (Cache::has($fd)) {
                foreach ($cache_datas as $cache_data) {
                    $this->_formatResult->setSuccess($cache_data);
                    $res = $this->_signReturn($this->_formatResult->getData());
                    $this->_swoole_ws_server->push($fd, $res);
                }
            } else {
                $set_cachetime = config('services')['save_voice_time']['exp'];
                if($set_cachetime){
                    Cache::put($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'] ,$cache_datas, $set_cachetime);
                }else{
                    Cache::forever($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'] ,$cache_datas);
                }
            }

            $this->_formatResult->setSuccess($new_data);
        }else{
            $this->_formatResult->setError('TTS.AUDIO.SRC.FAIL');
        }
        return $this->_signReturn($this->_formatResult->getData());

    }

    public function workVoicenotifyfetch($dataOri, $data, $bizContent, $bizContentFormat)
    {
        $user = User::where('id_merchant', $bizContentFormat['id_merchant'])->where('role','merchant')->first();

        if(empty($bizContentFormat['id_merchant']) || empty($user)){
            $this->_formatResult->setError('ID.MERCHANT.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }

        if(empty($bizContentFormat['type']) || empty(AudioTemplateConf::TYPE[$bizContentFormat['type']])){
            $this->_formatResult->setError('TYPE.INVALID');
            return $this->_signReturn($this->_formatResult->getData());
        }

        $src_arrs = \Cache::get($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'])??[];

        if(!empty($src_arrs)){

            $src = array_shift($src_arrs);

            $set_cachetime = config('services')['save_voice_time']['exp'];

            if($set_cachetime){
                \Cache::put($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'] ,$src_arrs, $set_cachetime);
            }else{
                \Cache::forever($bizContentFormat['type'].'_'.$bizContentFormat['id_merchant'] ,$src_arrs);
            }

            if(is_array($src)){
                $this->_formatResult->setSuccess($src);
                return $this->_signReturn($this->_formatResult->getData());
            }


            $this->_formatResult->setError('NOTIFY.VOICE.NULL');
            return $this->_signReturn($this->_formatResult->getData());
        } else{
            $this->_formatResult->setError('NOTIFY.VOICE.NULL');
            return $this->_signReturn($this->_formatResult->getData());
        }
        /*else{

        $amt = mt_rand(10,30);
        $voice_data = $this->_baidutts->getAudioSrc('10001', ['amt' => $amt]);

        $src = [
            "type" => "PAY_SUCCESS",
            "voice_src" => "https://pv.yaoqianba.com/storage/audio/摇钱八到账{$amt}元.mp3",
            "today_sum" => "388",
            "rel_text" => "摇钱吧到账{$amt}元",
            "order" => [
                "id_tradedetail" => 6860,
                "id_merchant" => 446,
                "amount_due" => $amt,
                "amount" => $amt,
                "discount" => 0,
                "mchreturn" => 0,
                "out_tradeno" => "153029167015120",
                "channel_tradeno" => "",
                "trade_status" => "1",
                "allpay_biz_channel" => "wx",
                "allpay_biz_type" => "wx.jspay",
                "allpay_merchantno" => "86570004",
                "allpay_terminalno" => "",
                "id_wxuser" => 935,
                "createtime" => "2018-06-30 01:01:10",
                "paytime" => "今天".date('H:i:s'),
                "is_balance" => null,
                "feerate" => 0,
                "fee" => "0.00",
                "is_subscribe" => 0,
                "is_get_redpack" => 0,
                "wxuser" => [
                    "id_wxuser" => 935,
                    "avatar_url" => "http://thirdwx.qlogo.cn/mmopen/vi_32/Ew3qktx1vy2jmLLtAaibKXyIqtKMaJS2KxZmEJDqFjwCIUFA16u1oicm5xBzgjy72k61iczuzFO3KS7JMX2wIocAA/132",
                    "nickname" => "Myron",
                    "nickname_encode" => "6IuP6IuP",
                    "email" => "",
                    "telephone" => "",
                    "gender" => "2",
                    "birthday" => "1970-01-01",
                    "province" => "江苏",
                    "city" => "徐州",
                    "district" => "",
                    "openid" => "o9xfWwv4-Phrw4QsV2breIZhkszE",
                    "unionid" => null,
                    "id_wxplatform" => 1,
                    "discount_tutorial" => 1,
                    "bonus" => "0.20",
                    "createtime" => "2018-03-07 14:28:31",
                    "country" => null,
                    "language" => null,
                    "privilege" => null,
                    "is_first_trade" => 1
                ],
            ]
        ];
        $this->_formatResult->setSuccess($src);
        return $this->_signReturn($this->_formatResult->getData());
    }*/
    }

}
